import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import 'package:xingsu/net/apis.dart';
import 'package:xingsu/net/http_manager.dart';

import '../model/Video_model.dart';

class VideoViewModel extends GetxController {
  int prevVideo = 0;
  int page = 0;
  RxList<VideoModel> videoDataList = <VideoModel>[].obs;
  final isPlaying = true.obs;
  List<VideoPlayerController> controllers = [];

  @override
  void onClose() {
    super.onClose();

    VideoPlayerController controller = controllers[prevVideo];
    controller.pause();

    for (VideoPlayerController controller in controllers) {
      controller.dispose();
    }
  }

  void playOrPause() {
    isPlaying.value = !isPlaying.value;
    if (isPlaying.value) {
      play();
    } else {
      pause();
    }
  }

  void changeVideo(int index) async {
    if (prevVideo != index) {
      VideoPlayerController preController = controllers[prevVideo];
      preController.seekTo(Duration.zero);
      preController.pause();

      VideoPlayerController controller = controllers[index];
      controller.play();
      prevVideo = index;
    }

    if (page == -1) {
      return;
    }
    if (index == videoDataList.length - 2) {
      print("加载下一页");
      page += 1;
      HttpManager.getInstance().get(Apis.homeList,
          params: {"from": page * 10, "limit": 10}, success: (resp) {
        int code = resp["code"];

        if (code == 0) {
          List<VideoModel> _datas = [];
          for (Map map in resp["data"] ?? []) {
            VideoModel model = VideoModel.fromJson(map);
            _datas.add(model);
          }

          videoDataList.addAll(_datas);

          controllers.addAll(_datas
              .map((element) =>
                  VideoPlayerController.network(element.videoPlayURL ?? "")
                    ..initialize()
                    ..setLooping(true))
              .toList());
        }
      });
    }
  }

  void loadVideo(int index) async {
    VideoPlayerController controller = controllers[index];
    controller.play();
  }

  void pause() {
    VideoPlayerController controller = controllers[prevVideo];
    controller.pause();
  }

  void play() {
    VideoPlayerController controller = controllers[prevVideo];
    controller.play();
  }
}
